package com.example.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.concurrent.Future;

/**
 * Asynchronous Tasks
 * @author Xu
 *
 */
@Slf4j
@Component
public class CatAsyncTask implements BeanFactoryAware {

    @Autowired
    private CatAsyncTask self;

    @CatAsync
    public Future<String> doTask1() throws InterruptedException{
        log.info("Task1 started.");
        long start = System.currentTimeMillis();
        Thread.sleep(5000);
        long end = System.currentTimeMillis();

        log.info("Task1 finished, time elapsed: {} ms.", end-start);

        return new AsyncResult<>("Task1 accomplished!");
    }

    public void doInnerAsync() throws InterruptedException {
        log.info("doInnerAsync------------------------------- started.");
        self.doTask1();
        log.info("doInnerAsync------------------------------- end.");
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
       // this.self = beanFactory.getBean(CatAsyncTask.class);
    }
}